const jwt = require('koa-jwt');
import 'reflect-metadata';
const Koa = require('koa');
const cors = require('@koa/cors');
const bodyParser = require('koa-bodyparser');
import { createConnection } from 'typeorm';

import {logger} from './logger';
// import router from './routes';
import { protectedRouter, unprotectedRouter } from './routes';
import { JWT_SECRET } from './constants';

createConnection().then(() => {
  const app = new Koa();
  
  // 注册中间件
  app.use(logger());
  app.use(cors());
  app.use(bodyParser());

  app.use(async (ctx, next) => {
    try {
      await next();
    } catch (err) {
      // 只返回 JSON 格式的响应
      ctx.status = err.status || 500;
      ctx.body = { message: err.message };
    }
  });
  
  // 响应用户请求
  // app.use( async (ctx) => {
  //   ctx.body = 'Hello Koa';
  // });
  // app.use(router.routes()).use(router.allowedMethods());

  // 无需 JWT Token 即可访问
  app.use(unprotectedRouter.routes()).use(unprotectedRouter.allowedMethods());

  // 注册 JWT 中间件
  app.use(jwt({ secret: JWT_SECRET }).unless({ method: 'GET' }));

  // 需要 JWT Token 才可访问
  app.use(protectedRouter.routes()).use(protectedRouter.allowedMethods());
  
  // 运行服务器
  app.listen(3000, '0.0.0.0');
}).catch((err: string) => console.log('TypeORM connection error:', err));

